package com.cqie.practicaltraining.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.practicaltraining.config.result.R;
import com.cqie.practicaltraining.domain.Enclosures;
import com.cqie.practicaltraining.domain.Fencing;
import com.cqie.practicaltraining.domain.Pasture;
import com.cqie.practicaltraining.dto.AddEnclosuresDto;
import com.cqie.practicaltraining.dto.EnclosuresDto;
import com.cqie.practicaltraining.dto.PageResult;
import com.cqie.practicaltraining.service.EnclosuresService;
import com.cqie.practicaltraining.mapper.EnclosuresMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 9977
 * @description 针对表【enclosures(圈舍)】的数据库操作Service实现
 * @createDate 2024-12-26 10:47:28
 */
@Service
public class EnclosuresServiceImpl extends ServiceImpl<EnclosuresMapper, Enclosures> implements EnclosuresService {
    @Autowired
    private PastureServiceImpl pastureService;
    @Autowired
    private FencingServiceImpl fencingService;
    @Override
    public R searchEnclosuresByCondition(EnclosuresDto enclosuresDto) {
        LambdaQueryWrapper<Enclosures> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(enclosuresDto.getEnclosuresName() != null, Enclosures::getEnclosuresName, enclosuresDto.getEnclosuresName())
                .like(enclosuresDto.getPastureName() != null, Enclosures::getPastureName, enclosuresDto.getPastureName())
                .eq(enclosuresDto.getStatus() != null, Enclosures::getStatus, enclosuresDto.getStatus());
        IPage<Enclosures> page = new Page<>(enclosuresDto.getPageNumber(), enclosuresDto.getPageSize());
        IPage<Enclosures> resultPage = page(page, wrapper);
        PageResult<Enclosures> result = new PageResult<>(resultPage.getRecords(), enclosuresDto.getPageNumber(), enclosuresDto.getPageSize(), resultPage.getTotal());
        if (!result.getRecords().isEmpty())
            return R.Success("查询成功", result);
        return R.Failed("暂无数据");
    }

    @Override
    public R saveEnclosure(AddEnclosuresDto addEnclosuresDto) {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pasture::getPastureName, addEnclosuresDto.getPastureName());
        if (pastureService.getOne(wrapper) == null)
            return R.Failed("该牧场不存在");
        Long pastureId = pastureService.getOne(wrapper).getPastureId();
        Enclosures enclosures = new Enclosures();
        enclosures.setPastureId(pastureId);
        enclosures.setEnclosuresName(addEnclosuresDto.getEnclosuresName());
        enclosures.setPastureName(addEnclosuresDto.getPastureName());
        if (getOne(new LambdaQueryWrapper<Enclosures>().eq(Enclosures::getEnclosuresName, addEnclosuresDto.getEnclosuresName())) != null)
            return R.Failed("该圈舍名称已存在");
        if (save(enclosures))
            return R.Success("添加成功");
        return R.Failed("添加失败");
    }

    @Override
    public R updateEnclosure(AddEnclosuresDto addEnclosuresDto) {
        // 检查必填字段
        if (addEnclosuresDto.getEnclosuresId() == null) {
            return R.Failed("请传入圈舍ID");
        }

        try {
            // 检查圈舍ID是否存在
            LambdaQueryWrapper<Enclosures> enclosuresIdWrapper = new LambdaQueryWrapper<>();
            enclosuresIdWrapper.eq(Enclosures::getEnclosuresId, addEnclosuresDto.getEnclosuresId());
            Enclosures existingEnclosures = getOne(enclosuresIdWrapper);
            if (existingEnclosures == null) {
                return R.Failed("该圈舍不存在");
            }

            // 检查牧场是否存在并获取牧场ID
            LambdaQueryWrapper<Pasture> pastureWrapper = new LambdaQueryWrapper<>();
            pastureWrapper.eq(Pasture::getPastureName, addEnclosuresDto.getPastureName());
            Pasture pasture = pastureService.getOne(pastureWrapper);
            if (pasture == null) {
                return R.Failed("该牧场不存在");
            }
            Long pastureId = pasture.getPastureId();

            // 检查圈舍名称是否已存在
            LambdaQueryWrapper<Enclosures> enclosuresNameWrapper = new LambdaQueryWrapper<>();
            enclosuresNameWrapper.eq(Enclosures::getEnclosuresName, addEnclosuresDto.getEnclosuresName())
                    .ne(Enclosures::getEnclosuresId, addEnclosuresDto.getEnclosuresId());
            if (getOne(enclosuresNameWrapper) != null) {
                return R.Failed("该圈舍名称已存在");
            }

            // 更新圈舍信息
            Enclosures enclosures = new Enclosures();
            enclosures.setPastureId(pastureId);
            enclosures.setEnclosuresName(addEnclosuresDto.getEnclosuresName());
            enclosures.setPastureName(addEnclosuresDto.getPastureName());
            enclosures.setUpdatedTime(new Date());
            enclosures.setEnclosuresId(addEnclosuresDto.getEnclosuresId());

            if (updateById(enclosures)) {
                return R.Success("修改成功");
            } else {
                return R.Failed("修改失败");
            }
        } catch (Exception e) {
            // 记录异常日志
            log.error("更新圈舍信息失败", e);
            return R.Failed("系统错误，请稍后再试");
        }
    }

    @Override
    public R updateEnclosureStatus(Long enclosureId) {
        LambdaQueryWrapper<Fencing> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Fencing::getEnclosuresId, enclosureId);
        if (fencingService.getOne(wrapper) != null) {
            if (fencingService.getOne(wrapper).getStatus() == 1)
                return R.Failed("该圈舍下有已启用的围栏，请先禁用围栏");
        }
        LambdaQueryWrapper<Enclosures> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Enclosures::getEnclosuresId, enclosureId);
        if (getOne(wrapper1) == null)
            return R.Failed("该圈舍不存在");
        Long pastureId = getOne(wrapper1).getPastureId();
        LambdaQueryWrapper<Pasture> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Pasture::getPastureId, pastureId);
        if (pastureService.getOne(wrapper2) == null)
            return R.Failed("牧场不存在");
        if (pastureService.getOne(wrapper2).getStatus() == 0)
            return R.Failed(pastureService.getOne(wrapper2).getPastureName() + "牧场未启用");
        Enclosures enclosures = new Enclosures();
        enclosures.setEnclosuresId(enclosureId);
        if (getOne(wrapper1).getStatus() == 1)
            enclosures.setStatus(0);
        else
            enclosures.setStatus(1);
        if (updateById(enclosures))
            return R.Success("修改成功");
        return R.Failed("修改失败");
    }
}




